#include "control.h"

static word aluOp;     // ALU operation
static word aluSrc;    // if nonzero, ALU second operand comes from a register
static word pcSrc;     // if nonzero, we may be jumping, but only if the condition register is nonzero too
static word pcReg;     // if nonzero, jump address comes from a register
static word regWrite;  // if nonzero, a value will be stored in a register
static word regData;   // if nonzero, the value to be stored in a register is from memory
static word memWrite;  // if nonzero, a value is stored in memory
static word memAddr;   // if nonzero, the address in memory is from a register
static word portWrite; // if nonzero, write to the IO bus
static word portRead;  // if nonzero, read from the IO bus

void set_flags (word opcode)
{
	aluOp = 0;
	aluSrc = UNSET;
	pcSrc = UNSET;
	pcReg = UNSET;
	regWrite = UNSET;
	regData = UNSET;
	memWrite = UNSET;
	memAddr = UNSET;
	portRead = UNSET;
	portWrite = UNSET;

	switch (opcode)
	{
		case ST:
			memWrite = SET;
			memAddr = SET;
			break;
		case STI:
			memWrite = SET;
			break;
		case LD:
			regWrite = SET;
			regData = SET;
			memAddr = SET;
			break;
		case LDI:
			regWrite = SET;
			regData = SET;
			break;
		case CALL:
			set_register (RA, get_pc () + 1);
		case J: 
			pcSrc = SET;
			pcReg = SET;
			break;
		case CALI:
			set_register (RA, get_pc () + 1);
		case JI:
			pcSrc = SET;
			break;
		case RD:
			portRead = SET;
			regWrite = SET;
			break;
		case WR:
			portWrite = SET;
			break;
		default:
			regWrite = SET;
			aluSrc = (opcode & 0x20) ? UNSET : SET;
			aluOp = opcode & ALU_MASK;
	}
}

word getRegWrite (void)
{
	return regWrite;
}

word getAluSrc (void)
{
	return aluSrc;
}

word getPcSrc (void)
{
	return pcSrc;
}

word getMemWrite (void)
{
	return memWrite;
}

word getRegData (void)
{
	return regData;
}

word getAluOp (void)
{
	return aluOp;
}

word getMemAddr (void)
{
	return memAddr;
}

word getPcReg (void)
{
	return pcReg;
}

word getPortRead (void)
{
	return portRead;
}

word getPortWrite (void)
{
	return portWrite;
}

